package br.com.freelancer.persistencia;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.freelancer.modelo.ModeloBase;

/**
 * Implementação de Persistencia Generica.
 * @author Luis Garcia
 */
@Repository
@Transactional
public abstract class GenericDAOImpl<PK extends Serializable, T extends ModeloBase> extends HibernateDaoSupport implements IGenericDAO<T, PK> {
	
	private Class<T> persistentClass;

	@SuppressWarnings("unchecked")
	public GenericDAOImpl() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public abstract void init(SessionFactory sessionFactory);
	
	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	protected transient Log log = LogFactory.getLog(this.getClass());
	
	public T findById ( PK id, boolean lock ){
		if ( id == null ) {
			throw new IllegalArgumentException( "O id do objeto não pode ser nulo - GenericDAOImpl.findById - " + persistentClass.getName() );
		}
		if (log.isTraceEnabled()) {
            log.trace(">>> findById(" + getPersistentClass().getSimpleName() + ", " + id + ")");
        }
		if (lock) { 
			return (T) getHibernateTemplate().get(getPersistentClass(), id, LockMode.PESSIMISTIC_WRITE);
		} else {
			return (T) getHibernateTemplate().get(getPersistentClass(), id);
		}
	}
	
	public T findById ( PK id ){
		return findById(id, false);
	}
	
	@java.lang.SuppressWarnings("unchecked")
	public PK save(T entity) {
        if (entity == null) {
        	throw new IllegalArgumentException( "O objeto não pode ser nulo - GenericDAOImpl.save - " + persistentClass.getName() );
        }
        if (log.isTraceEnabled()) {
            log.trace(">>> save(" + entity + ")");
        }
        entity = (T) getHibernateTemplate().save(entity);
        if (log.isTraceEnabled()) {
            log.trace("<<< save(" + entity + ")");
        }
        return (PK) entity.getId();
    }
	
	public T update(T entity) {
        if (entity == null) {
        	throw new IllegalArgumentException( "O objeto não pode ser nulo - GenericDAOImpl.updade - " + persistentClass.getName() );
        }
        if (log.isTraceEnabled()) {
            log.trace(">>> update(" + entity + ")");
        }
        getHibernateTemplate().update(entity);
        if (log.isTraceEnabled()) {
            log.trace("<<< update(" + entity + ")");
        }
        return entity;
    }
	
	public T saveOrUpdate(T entity) {
        if (entity == null) {
        	throw new IllegalArgumentException( "O objeto não pode ser nulo - GenericDAOImpl.saveOrUpdade - " + persistentClass.getName() );
        }
        if (log.isTraceEnabled()) {
            log.trace(">>> saveOrUpdate(" + entity + ")");
        }
        entity = (T) getHibernateTemplate().merge(entity);
        if (log.isTraceEnabled()) {
            log.trace("<<< saveOrUpdate(" + entity + ")");
        }
        return entity;
    }
	
	public void delete(T entity) {
        if (entity == null) {
        	throw new IllegalArgumentException( "O objeto não pode ser nulo - GenericDAOImpl.delete - " + persistentClass.getName() );
        }
        if (log.isTraceEnabled()) {
            log.trace(">>> delete(" + entity + ")");
        }
        getHibernateTemplate().delete(entity);
        if (log.isTraceEnabled()) {
            log.trace("<<< delete(" + entity + ")");
        }
    }
	
	public List<T> findAll() {
        if (log.isTraceEnabled()) {
            log.trace(">>> findAll(" + getPersistentClass().getSimpleName() + ")");
        }
        List<T> objList = (List<T>) getHibernateTemplate().loadAll(getPersistentClass());
        if (log.isTraceEnabled()) {
            log.trace("<<< findAll(" + getPersistentClass().getSimpleName() + ") : " + objList);
        }
        return objList;
    }

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Criterion... criterion) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}
	
	public void flush() {
		getHibernateTemplate().flush();
	}

	public void clear() {
		getHibernateTemplate().clear();
	}

}
